package com.xzkj.xiaozhengblog;

import com.xzkj.xiaozhengblog.data.ArtList;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import static com.xzkj.xiaozhengblog.main.getConn;

public class artlist {
    //获取首页资讯

    public static String getindexartlist() {
        main.getConn();
        String data = "<div class=\"item\">\n" +
                "                <div id=\"java\" class=\"title\"><h1>%Tab%</h1></div>\n" +
                "                <div class=\"status\">发布于:%时间%|阅读:%阅读%|收藏%收藏%</div>\n" +
                "                <div class=\"content\">\n" + "%内容%\n" +
                "                </div>\n" +
                "            </div>";
        String returndata = "";
        try {
            List<ArtList> listArt = getArtList();
            for (ArtList art : listArt) {
                String datamb = data;
                datamb.replace("%Tab%",art.tab);
                datamb.replace("%时间%",art.dateart.toString());
                datamb.replace("%阅读%",art.reading);
                datamb.replace("%收藏%",art.collection);
                datamb.replace("%内容%",art.text);
                returndata = returndata + datamb;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return returndata;
    }

    //连接数据库获取值

    public static List<ArtList> getArtList() throws SQLException {
        //创建查询语句
        String sql = "SELECT id,username,tab,dateart,reading,collection,text FROM artlist";
        //创建ps
        PreparedStatement ps = null;
        try {
            ps = getConn().prepareStatement(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        ResultSet rs = null;
        try {
            assert ps != null;
            rs = ps.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        assert rs != null;
        List<ArtList> artlist = new ArrayList<>();
        while (rs.next()) {
            ArtList dataArtlist = new ArtList();
            dataArtlist.id = rs.getString("id");
            dataArtlist.tab = rs.getString("tab");
            dataArtlist.collection = rs.getString("collection");
            dataArtlist.reading = rs.getString("reading");
            dataArtlist.dateart = rs.getDate("dateart");
            dataArtlist.text = rs.getString("text");
            dataArtlist.username = rs.getString("username");
            artlist.add(dataArtlist);
        }
        return artlist;

    }


}
